package com.zhu.storesmanager;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.models.ModelItem;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.SalesData;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 型号查询结果界面
 */
public class SalesInquiryResultActivity extends Activity implements View.OnClickListener{

	public final static String MODEL = "model"; //数据key
	public final static String PFL = "pfl";
	//异步查询数据库token
	private final static int MODEL_LIST_QUERY_TOKEN = 0; //查询所有型号 token 
	private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler
	private List<ModelItem> mModelList = new ArrayList<ModelItem>(); //所有查询结果型号列表集合

	private TextView mTitleView = null; //标题栏
	private LinearLayout mBodyView = null; //所有型号列表内容界面
	private String mModel, mPfl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_salesnquiryresult); //设置显示界面布局
		mModel = this.getIntent().getStringExtra(MODEL); //获取传递查询条件数据
		mPfl = this.getIntent().getStringExtra(PFL);
		setupViews();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupViews(){
		mTitleView = (TextView)findViewById(R.id.title_text);
		mBodyView = (LinearLayout)findViewById(R.id.list_body);
		findViewById(R.id.ssresule_menu_back).setOnClickListener(this);
		findViewById(R.id.ssresule_menu_save).setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mDataQueryHandler = new DataQueryHandler(getContentResolver());
		mTitleView.setText(R.string.salesinquiryresult);
		startQueryModelsList();
	}

	/**
	 * 开始查询型号列表
	 */
	private void startQueryModelsList(){
		String where = DataUtils.getSearchModelWhere(mModel, mPfl);
//		//根据输入条件生成查询条件
//		if(mModel != null && mModel.length() == 2 && mPfl != null && mPfl.length() == 4){
//			where = StoresManagerSettings.ModelsColumns.MODELS_NAME + " LIKE \'%" + mModel + "PFL" + mPfl +"%\'";
//		}else if(mModel != null && mModel.length() == 2 && (mPfl == null || mPfl.length() == 0)){
//			where = StoresManagerSettings.ModelsColumns.MODELS_NAME + " LIKE \'%" + mModel + "PFL" +"%\'";
//		}else if((mModel == null || mModel.length() == 0) && (mPfl != null && mPfl.length() == 4)){
//			where = StoresManagerSettings.ModelsColumns.MODELS_NAME + " LIKE \'%PFL" + mPfl +"%\'";
//		}
		if(Actions.DEBUG)
			Log.d("zhu", "where=" + where);
		if(where != null){
			mDataQueryHandler.startQuery(MODEL_LIST_QUERY_TOKEN, null, 
					StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION,
					null, where, null, null);
		}else{
			Log.e("zhu", "error startQueryModelsList " + mModel + "," + mPfl);
		}
	}

	/**
	 * 更具查询结果更新型号列表
	 * @param cursor 查询结果数据
	 */
	private void updateModelListFromCursor(Cursor cursor){
		if(mModelList != null){
			mModelList.clear(); //清空数据
		}
		try {
            final int modleNameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ModelsColumns.MODELS_NAME);
            while (cursor.moveToNext()) {//遍历所有型号数据
            	ModelItem item = new ModelItem();
            	item.mName = cursor.getString(modleNameIndex);
            	SalesData.getInstance(this).updateModelQuantity(item);
            	mModelList.add(item); //加入数据集
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateModelListFromCursor error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
		updateBodyList();
	}

	/**
	 * 更新型号列表界面
	 */
	private void updateBodyList(){
		mBodyView.removeAllViews(); //清空数据
		for(int i = 0; i < mModelList.size(); i++){ //添加所有列表数据
			View view = getView(mModelList.get(i));
			mBodyView.addView(view);
		}
	}

	/**
     * 获取型号列表项界面
     * @param item 型号数据
     */
    private View getView(ModelItem item) {
        View view = LayoutInflater.from(this).inflate(R.layout.model_item, null);
        ((TextView)view.findViewById(R.id.model_name)).setText(item.mName);
        EditText edittext = (EditText)view.findViewById(R.id.model_text);
        EditText priceedittext = (EditText)view.findViewById(R.id.model_price);
        if(item.mQuantity != Integer.MIN_VALUE){
        	edittext.setText("" + item.mQuantity);
        }
        if(item.mPrice != Integer.MIN_VALUE){
        	priceedittext.setText("" + item.mPrice);
        }
        view.setTag(item);
        return view;
    }

	/**
	 * 异步数据查询
	 */
	private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        /**
         * 查询结果返回
         * (non-Javadoc)
         * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case MODEL_LIST_QUERY_TOKEN:
                	updateModelListFromCursor(cursor);
                    break;
                default:
                    Log.e("zhu", "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

	/**
	 * (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.ssresule_menu_back:  //返回
					finish();
					break;
				case R.id.ssresule_menu_save: //保存
					saveData(this, mBodyView, false);
					setResult(Activity.RESULT_OK);
					finish();
					break;
			}
		}
	}

	/**
	 * 保存数据
	 */
	public static void saveData(Context context, LinearLayout bodyView, boolean isShowToast){
		List<ModelItem> updateList = new ArrayList<ModelItem>(); //需要更新的数据
		List<ModelItem> deleteList = new ArrayList<ModelItem>(); //需要删除的数据
		for(int i = 0; i < bodyView.getChildCount(); i++){
			View v = bodyView.getChildAt(i);
			EditText text = (EditText)v.findViewById(R.id.model_text);//获取填入的销量数据
			EditText priceText = (EditText)v.findViewById(R.id.model_price);//获取填入的价格数据
			ModelItem item = (ModelItem)v.getTag();
			int curCount = getValue(text); //读取销量
			int price = getValue(priceText); //读取价格

			if(item.mQuantity != curCount || item.mPrice != price){
				if(curCount != Integer.MIN_VALUE && price != Integer.MIN_VALUE){
					item.mQuantity = curCount;
					item.mPrice = price;
					updateList.add(item);
				}else{
					deleteList.add(item);
				}
			}
		}
		//更新数据
		if((updateList != null && updateList.size() > 0) || (deleteList != null && deleteList.size() > 0)){
			SalesData.getInstance(context).updateSalesData(updateList, deleteList);
		}
		//清空数据
		updateList.clear();
		updateList = null;
		deleteList.clear();
		deleteList = null;
		if(isShowToast){
		    Actions.toastShort(context, context.getResources().getString(R.string.datasave_success));   
		}
	}

	/**
	 * 获取输入的数据文本
	 * @param text 文本况
	 * @return data 返回数据
	 */
	public static int getValue(EditText text){
		String str = text.getText().toString();
		int data = Integer.MIN_VALUE; 
		if(str == null || str.length() == 0){ //输入的内容为空
			data = Integer.MIN_VALUE;
		}else{//不为空
			try{
				data = Integer.parseInt(str);
			}catch(Exception e){
				Log.e("zhu", "str="+str);
				data = Integer.MIN_VALUE;
			}
		}
		return data;
	}
}
